<?php

namespace App\Models\Access\Role;

use App\Models\Access\User\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use App\Models\Access\Role\Traits\RoleAccess;
// use App\Models\Access\Role\Traits\Attribute\RoleAttribute;
use App\Models\Access\Role\Traits\Relationship\RoleRelationship;
use Illuminate\Support\Facades\Validator;

/**
 * Class Role
 * @package App\Models\Access\Role
 */
class Role extends Model
{
    // use RoleAttribute;
    use RoleAccess, RoleRelationship;

    //超级管理员
    const ROLE_SUPER_ADMIN = 1;
    //管理员
    const ROLE_ADMIN = 2;
    //审核员
    const ROLE_AUDIT_ADMIN = 3;

    //拥有权限值
    const ACCESS_ALL = 1;
    //部分最大权限
    const ACCESS_PART = 2;
    public $timestamps = true;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'sort'];

    /**
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->table = 'roles';
    }

    /**
     * 列表信息
     * @param string $where
     * @return array
     */
    public function getList($where=[],$fields='*'){
        /*$user = User::find(1);
        dd(Role::all()->permissions);*/
        $list = DB::table('roles')->select($fields);

        if (!empty($where)){

            $list->where('name','like','%'.$where.'%');

        }
        $list->orderBy('sort','DESC');
        return $list->get();
    }

    /**
     * 集合
     * @param integer $uid
     */
    public function getRoles ($rid){

        $roles = $this->with('permissions')->find($rid);

        return $roles;
    }

    /**
     * 记录数
     * @param array $where
     * @return integer
     */
    public static function getCount($where){

        if (!empty($where)){

            return DB::table('roles')
                ->where('name','like','%'.$where.'%')
                ->count();

        } else {
            return DB::table('roles')->count();

        }
    }

    /**
     * 插入记录
     * @param mixed $request
     * @return bool
     */
    public function insertRow($request){

        return DB::transaction(function() use ($request){
            $id = $this->create($request->input())->id;

            if(intval($id) > 0){
                //更新权限
                $roles = $this->find($id);
                if (!empty($request->permissions))
                    $roles->attachPermissions($request->permissions);
                return true;
            }
            throw new \Exception('权限添加失败');

        });
    }

    /**
     * 修改记录
     * @param mixed $request
     * @return bool
     */
    public function updateRow($request){

        return DB::transaction(function() use ($request){
            $role = $this->find($request->id);

            if($role->update($request->input())){
                //更新权限
                $role->savePermissions($request->permissions);
                return true;
            }
            throw new \Exception('权限更新失败');

        });
    }

    /**
     * 删除记录
     * @param mixed $request
     * @return bool
     */
    public function deleteRow($request){

        $role = $this->find($request->id);
        //超级管理员
        if ($role->id == 1) {
            throw new \Exception('超级管理员不能删除');
        }

        if ($role->users()->count() > 0) {
            throw new \Exception('该角色下有用户');
        }

        return DB::transaction(function() use ($role) {
            //删除所有权限
            $role->permissions()->sync([]);

            if ($role->delete()) {
                return true;
            }

            throw new \Exception('角色删除失败');
        });

    }

    /**
     * validate 表单数据验证
     * @parma $type add or update
     * @param $data
     * @return bool
     */
    public static function validate ($data,$type='add') {
        if ($type == 'update'){
            return Validator::make($data, [
                'name' => 'required'
            ], [
                'name.required' => '请填写角色！'
            ]);
        }else{
            return Validator::make($data, [
                'name' => 'required|unique:roles'
            ], [
                'name.required' => '角色为空或已存在！'
            ]);
        }

    }
}
